﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Interfaces.Common;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Entitys.Common.Dto.PrintTemplateCustomer;
using Spire.Doc;
using SHZY.Common.Models;
using SHZY.Common.Security;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：客户打印模板.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "PrintTemplateCustomer", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBasePrintTemplateCustomerService : IComBasePrintTemplateCustomerService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBasePrintTemplateCustomerEntity> _repository;
    private readonly ISqlSugarRepository<ComBaseCustomerEntity> _basecustomer;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="ComBasePrintTemplateCustomerService"/>类型的新实例.
    /// </summary>
    public ComBasePrintTemplateCustomerService(
        ISqlSugarRepository<ComBasePrintTemplateCustomerEntity> wmsBasePrintTemplateCustomerRepository, IUserManager userManager, ISqlSugarRepository<ComBaseCustomerEntity> basecustomer)
    {
        _repository = wmsBasePrintTemplateCustomerRepository;
        _userManager = userManager;
        _basecustomer = basecustomer;
    }

    /// <summary>
    /// 获取客户打印模板.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        //var data = (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBasePrintTemplateCustomerInfoOutput>();
        //var customercode = _basecustomer.Context.Queryable<ComBaseCustomerEntity>().Where(a => a.Id == data.customerId).Select(a => a.Code).ToList();
        //return new ComBasePrintTemplateCustomerCodeInfo { data = data, customercode = customercode };
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBasePrintTemplateCustomerInfoOutput>();
    }
    public class ComBasePrintTemplateCustomerCodeInfo
    {
        public ComBasePrintTemplateCustomerInfoOutput data { get; set; }
        public List<string> customercode { get; set; }
    }

    /// <summary>
    /// 获取客户打印模板列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] ComBasePrintTemplateCustomerListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity, ComBaseCustomerEntity>((it, b) => new JoinQueryInfos(JoinType.Left, it.CustomerId == b.Id))
            .WhereIF(!string.IsNullOrEmpty(input.templateId), it => it.TemplateId.Equals(input.templateId))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.CustomerId.Contains(input.keyword))
            .WhereIF(!string.IsNullOrEmpty(input.customer), (it, b) => b.Code.Contains(input.customer) || b.Name.Contains(input.customer))
            .Where(it => it.DeleteMark == null)
            .Select((it, b) => new ComBasePrintTemplateCustomerListOutput
            {
                id = it.Id,
                customerId = it.CustomerId,
                //customerCode = b.Code,
                customerCode=it.CustomerId,
                customerName = b.Name,
                templateId = it.TemplateId,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
            }).MergeTable();
            //.OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id);
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it => it.id);
        }

        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<ComBasePrintTemplateCustomerListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建客户打印模板.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] ComBasePrintTemplateCustomerCrInput input)
    {
        //var data = await _basecustomer.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1).Where(x => x.Code == input.customerId).ToListAsync();
        if (await _repository.AnyAsync(x => x.TemplateId == input.templateId && x.CustomerId == input.customerId && x.DeleteMark == null))
            throw Oops.Oh("当前客户已维护打印模板");
        var entity = input.Adapt<ComBasePrintTemplateCustomerEntity>();
        //entity.CustomerId = data.First().Id;
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (isOk < 1)
            throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 更新客户打印模板.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] ComBasePrintTemplateCustomerUpInput input)
    {
        //var data = await _basecustomer.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1).Where(x => x.Code == input.customerId).ToListAsync();
        if (await _repository.AnyAsync(x => x.Id != input.id && x.TemplateId == input.templateId && x.CustomerId == input.customerId && x.DeleteMark == null))
            throw Oops.Oh("当前客户已维护打印模板");
        var entity = input.Adapt<ComBasePrintTemplateCustomerEntity>();
        //entity.CustomerId = data.First().Id;
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除客户打印模板.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<ComBasePrintTemplateCustomerEntity>().SetColumns(it => new ComBasePrintTemplateCustomerEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }
}